import json

from flask import Blueprint, render_template, abort, request, jsonify

from extensions import db
from orms import ArticleORM, UserORM, CommentORM, CommentLikeORM
from orms.category import CategoryORM
from flask_jwt_extended import jwt_required, get_current_user

article_bp = Blueprint('article', __name__)


@article_bp.get('/article/')
@jwt_required(optional=True)
def articles_view():
    current_user: UserORM = get_current_user()
    # 首页文章数据
    page = request.args.get('page', type=int, default=1)
    per_page = request.args.get('limit', type=int, default=10)

    q = db.select(ArticleORM)
    # 筛选查询
    cid = request.args.get('cid', type=int, default=1)
    print("????????????????????????????????????????????????????")
    print(cid)
    if cid != 1:
        q = q.where(ArticleORM.category_id == cid)
        q = q.order_by(ArticleORM.id)
    q = q.order_by(ArticleORM.create_at.desc())

    pag = db.paginate(q, page=page, per_page=per_page, error_out=False)

    article_list = pag.items

    cate_list = CategoryORM.query.all()
    # 热门文章
    side_q = db.select(ArticleORM).order_by(ArticleORM.clicks.desc()).limit(15)
    click_article = db.session.execute(side_q).scalars()
    # print(click_article)
    return render_template(
        'article.html',
        current_user=current_user,
        article_list=article_list,
        cate_list=cate_list,
        pag=pag,
        click_article=click_article,
    )


@article_bp.route('/article/<int:a_id>', methods=['GET', 'POST'])
@jwt_required(optional=True)
def article_view(a_id):
    if request.method == 'GET':
        current_user = get_current_user()
        cate_list = CategoryORM.query.all()
        # 热门文章
        side_q = db.select(ArticleORM).order_by(ArticleORM.clicks.desc()).limit(10)
        click_article = db.session.execute(side_q).scalars()

        # 文章内容
        article: ArticleORM = ArticleORM.query.get(a_id)
        article.clicks += 1
        article.save()
        clicks = article.clicks
        if not article:
            abort(404)
        # 判断是否已经收藏
        is_collected = False
        if current_user and article in current_user.collection_article_list:
            is_collected = True
        return render_template(
            'detail.html',
            clicks=clicks,
            current_user=current_user,
            cate_list=cate_list,
            click_article=click_article,
            article=article,
            is_collected=is_collected
        )
    else:
        current_user: UserORM = get_current_user()
        article_id = request.json.get('article_id')
        content = request.json.get('comment')
        parent_id = request.json.get('parent_id')  # 父评论 id
        print("----------------------------------------------------")
        print(request.json)
        comment: CommentORM = CommentORM()
        if content:
            comment.content = content
            # 子评论
            if parent_id:
                comment.parent_id = parent_id
            # 添加文章关系
            comment.article_id = article_id
            db.session.flush()
            # 添加用户
            current_user.comment_list.append(comment)
            db.session.add(comment)
            db.session.commit()
            return {
                'code': 0,
                'message': '评论成功'
            }
        return {
            'code': -1,
            'message': '不能发表空评论'
        }


@article_bp.post('/article/article_collection/')
@jwt_required()
def article_collection():
    # 1. 获取文章
    aid = request.json.get('article_id')
    action = request.json.get('action')
    article: ArticleORM = ArticleORM.query.get(aid)
    current_user: UserORM = get_current_user()
    message = ''
    if action == 'collect':
        current_user.collection_article_list.append(article)
        message = '收藏文章'
    elif action == 'cancel_collect':
        current_user.collection_article_list.remove(article)
        message = '取消收藏'
    current_user.save()
    return {
        'code': 0,
        'message': message
    }


@article_bp.post('/article/article_comment/')
@jwt_required()
def article_comment():
    current_user: UserORM = get_current_user()
    data = request.get_json(force=True)
    print(data)
    article_id = data['article_id']
    content = data['comment']
    parent_id = data.get('parent_id')
    print("----------------------------------------------------")
    print(request.json)
    comment: CommentORM = CommentORM()
    if content:
        comment.content = content
        # 子评论
        if parent_id:
            comment.parent_id = parent_id
        # 添加文章关系
        comment.article_id = article_id
        db.session.flush()
        # 添加用户
        current_user.comment_list.append(comment)
        db.session.add(comment)
        db.session.commit()
        return {
            'code': 0,
            'message': '评论成功'
        }
    return {
        'code': -1,
        'message': '不能发表空评论'
    }


@article_bp.post('/article/comment_like/')
@jwt_required()
def comment_like_view():
    comment_like: CommentLikeORM = CommentLikeORM()
    action = request.json.get('action')
    comment_id = request.json.get('comment_id')
    current_user: UserORM = get_current_user()
    message = ''
    if action == 'add':  # 添加点赞
        comment_like.comment_id = comment_id
        # comment_like.user_id = current_user.id
        db.session.flush()
        current_user.comment_like_list.append(comment_like)
        db.session.add(comment_like)
        db.session.commit()
        message = '点赞成功'
    elif action == 'remove':  # 取消点赞
        comment_like: CommentLikeORM = CommentLikeORM.query.filter_by(comment_id=comment_id,
                                                                      user_id=current_user.id).first()
        # current_user.comment_like_list.remove(comment_like) ---> 错误方法
        db.session.delete(comment_like)
        db.session.commit()
        message = '取消成功'
    return {
        'code': 0,
        'message': message
    }


# 关注
@article_bp.post('/article/followed_user/')
@jwt_required()
def followed_user():
    current_user: UserORM = get_current_user()
    action = request.json.get('action')
    user_id = request.json.get('user_id')
    message = ''
    # 作者
    author: UserORM = UserORM.query.get(user_id)
    if action == 'follow':
        # 作者新增粉丝
        author.follower_list.append(current_user)
        db.session.commit()
        message = '关注成功'
    elif action == 'unfollow':
        # follower: UserORM = UserORM.query.filter_by(user_id=user_id, follower_id=current_user.id).first()
        author.follower_list.remove(current_user)
        db.session.commit()
        message = '取消成功'
    return {
        "code": 0,
        "message": message
    }


@article_bp.route('/load_more', methods=['POST'])
def load_more():
    last_article_id = request.form.get('lastArticleId')
    # Simulate getting new articles from the database
    new_articles = get_new_articles(last_article_id)
    return jsonify(new_articles=new_articles, pages=5)


@article_bp.route('/append_data/', methods=['POST'])
def append_data():
    last_article_id = request.form.get('lastArticleId')
    # Simulate getting new articles from the database
    new_articles = get_new_articles(last_article_id)
    # Append new articles to the existing ones
    existing_articles = request.form.get('existingArticles')
    print('[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[')
    print(existing_articles)
    if existing_articles is None:
        existing_articles = []
    else:
        existing_articles = json.loads(existing_articles)
    existing_articles.extend(new_articles)
    return jsonify(new_articles=existing_articles, pages=5)


def get_new_articles(last_article_id):
    # Query the database for articles with an id greater than last_article_id
    new_articles = ArticleORM.query.filter(ArticleORM.id > last_article_id).limit(5).all()
    if not new_articles:
        return ["文章已经到底了"]
    return [article.to_dict() for article in new_articles]
